//
//  PersonalProfileViewController.m
//  dangdang
//
//  Created by air on 16/1/25.
//  Copyright © 2016年 luweijie. All rights reserved.
//

#import "PersonalProfileViewController.h"
#import "ReviseNameViewController.h"
#import "ASIFormDataRequest.h"
#import "PersonalViewController.h"
#import "UIImageView+WebCache.h"

@interface PersonalProfileViewController ()<NSURLSessionDataDelegate, NSURLSessionDelegate, NSURLSessionTaskDelegate, UIPickerViewDataSource, UIPickerViewDelegate>

@property (nonatomic, strong) UIView * backView;
@property (nonatomic, strong) UIView * buttonView;
@property (nonatomic, strong) UIView * lineView;
@property (nonatomic, strong) UIButton * topButton;
@property (nonatomic, strong) UIButton * bottomButton;
@property (nonatomic, strong) NSData * imageData;
@property (strong,nonatomic)NSURLSession * session;
@property (nonatomic, copy) NSString * urlString;


@property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, strong) UIToolbar *toolBar;
@property (nonatomic, copy) NSString *tempSex;

@end

@implementation PersonalProfileViewController




- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self connection];
    
    [self updateUI];
   
   [self parperSexLabel];
   
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"hk_back_white@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    
    self.title = @"个人资料";
}

-(void)parperSexLabel{
   self.sexLabel.inputView = self.pickerView;
   self.sexLabel.inputAccessoryView = self.toolBar;
}

- (void)back{
    PersonalViewController * personboardVC = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"PersonalViewController"];

    [self.navigationController pushViewController:personboardVC animated:YES];
}

- (void)connection{
    NSString * token = userObject.accessToken;
    NSString * userIDString = userObject.userID;
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:token forKey:@"token"];
    [params setObject:userIDString forKey:@"uid"];
    
    [self postRequestWithMethodName:@"user/get_info" andParams:params andSender:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    NSString *resultDict=[[NSString alloc] initWithData:request.responseData encoding:request.responseEncoding] ;
    NSLog(@"result = %@", resultDict);
    NSLog(@"上传头像返回");
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSLog(@"上传头像失败");
}

//解析数据
- (NSMutableDictionary *)paramrequest:(ASIHTTPRequest *)request
{
    NSString *resultDict=[[NSString alloc] initWithData:request.responseData encoding:request.responseEncoding] ;
    NSDictionary *dict=[request userInfo];
    
    NSMutableDictionary *paramsDict=[[NSMutableDictionary alloc] init];
    if(resultDict!=nil)
    {
        [paramsDict setObject:resultDict forKey:@"Data"];
    }
    for(NSString *key in [dict allKeys])
    {
        [paramsDict setObject:[dict objectForKey:key] forKey:key];
    }
    return paramsDict;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)updateUI{
    _headSculptureImageView.layer.cornerRadius = _headSculptureImageView.bounds.size.width / 2;
    _headSculptureImageView.layer.masksToBounds = YES;
}
- (IBAction)personalButtonArray:(UIButton *)sender {
    if (sender.tag == 0 || sender.tag == 2) {
       
       
       
        UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removeView)];
        tap.numberOfTapsRequired = 1;
        
        _backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
        _backView.backgroundColor = [UIColor colorWithRed:10/255.0 green:10/255.0 blue:10/255.0 alpha:0.2];
        [_backView addGestureRecognizer:tap];
        [self.view.window addSubview:_backView];
        
        _buttonView = [[UIView alloc] initWithFrame:CGRectMake(80, self.view.center.y - 50, [UIScreen mainScreen].bounds.size.width - 160, 101)];
        _buttonView.backgroundColor = [UIColor whiteColor];
        _buttonView.layer.cornerRadius = 8;
        [_backView addSubview:_buttonView];
        
        _topButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, _buttonView.bounds.size.width, _buttonView.bounds.size.height / 2)];
        [_topButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_topButton addTarget:self action:@selector(imageOrSexButton:) forControlEvents:UIControlEventTouchUpInside];
        
        _bottomButton = [[UIButton alloc] initWithFrame:CGRectMake(0, _buttonView.bounds.size.height / 2 + 1, _buttonView.bounds.size.width, _buttonView.bounds.size.height / 2)];
        [_bottomButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_bottomButton addTarget:self action:@selector(imageOrSexButton:) forControlEvents:UIControlEventTouchUpInside];
        
        _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, _buttonView.bounds.size.height / 2, _buttonView.bounds.size.width, 1)];
        _lineView.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.5];
        if (sender.tag == 0) {
           
            [_topButton setTitle:@"相机" forState:UIControlStateNormal];
            [_bottomButton setTitle:@"相册" forState:UIControlStateNormal];
            _topButton.tag = 1;
            _bottomButton.tag = 2;
        }else{
            [_topButton setTitle:@"男" forState:UIControlStateNormal];
            [_bottomButton setTitle:@"女" forState:UIControlStateNormal];
            _topButton.tag = 3;
            _bottomButton.tag = 4;
        }
        [_buttonView addSubview:_topButton];
        [_buttonView addSubview:_bottomButton];
        [_buttonView addSubview:_lineView];
        
    }else if (sender.tag == 1){
        ReviseNameViewController *reviseboardVC = [[UIStoryboard storyboardWithName:@"ReviseNameViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"ReviseNameViewController"];
        reviseboardVC.PersonalProfileViewController = self;
        [self.navigationController pushViewController:reviseboardVC animated:YES];
    }
}

- (void)removeView{
    [_backView removeFromSuperview];
}

- (void)imageOrSexButton:(UIButton *)button{
    if (button.tag == 1) {
        [_backView removeFromSuperview];
        
        UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }else if (button.tag == 2){
        [_backView removeFromSuperview];
        
        UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }else{
        _sexLabel.text = button.titleLabel.text;
        
        NSString * token = userObject.accessToken;
        NSString * uid = userObject.userID;
        
        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
        [params setObject:token forKey:@"token"];
        [params setObject:uid forKey:@"uid"];
        [params setObject:@"0" forKey:@"udevice"];
        if ([_sexLabel.text isEqualToString:@"男"]) {
            [params setObject:@"0" forKey:@"usex"];
        }else if ([_sexLabel.text isEqualToString:@"女"]){
            [params setObject:@"1" forKey:@"usex"];
        }
        
        [self postRequestWithMethodName:@"user/modify" andParams:params andSender:nil];
        [LoadingView showInView:self.view image:nil info:@"通讯中，请稍候..." animated:YES modeled:YES autoHide:NO];
        
        [_backView removeFromSuperview];
    }
}

#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName{
    _imageData = UIImageJPEGRepresentation(currentImage, 1);
    
    //获取沙盒目录
    NSString * fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];

    //将图片写入文件
    [_imageData writeToFile:fullPath atomically:NO];
}

#pragma mark - 选择完成后调用该方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:^{}];
   
   userObject.personString = nil;
    
    UIImage * image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    //保存图片之本地，上传图片到服务器需要使用
    [self saveImage:image withName:@"avatar.png"];
    
    NSString * fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"avatar.png"];
    
    UIImage * savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
    
    NSString * token = userObject.accessToken;
    NSString * userIDString = userObject.userID;
    NSString * urlString = [NSString stringWithFormat:@"%@%@",URLDoman,@"user/upload_headimg_bytes"];
    
    NSData *data = UIImagePNGRepresentation(savedImage);
    
    NSURL *url = [NSURL URLWithString:urlString];
    
    ASIFormDataRequest* request = [ASIFormDataRequest requestWithURL:url];
    request.tag = 0x01;
    request.delegate = self;
    [request setRequestMethod:@"POST"];
    [request setTimeOutSeconds:90];
    [request addPostValue:token forKey:@"token"];
    [request addPostValue:userIDString forKey:@"uid"];
    [request addData:data withFileName:@"avatar.png" andContentType:@"image/png" forKey:@"attach"];
    [request startAsynchronous];
    
    //设置图片显示
    [_headSculptureImageView setImage:savedImage];
}

#pragma mark - 选择按取消按钮调用该方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)addImageView{
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    NSURL *url = [NSURL URLWithString:
                  _urlString];
    NSURLSessionDownloadTask *downloadPhotoTask =[[NSURLSession sharedSession]
                                                  downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
                                                      
                                                      NSLog(@"error = %@", error);
                                                      [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                                                      UIImage *downloadedImage = [UIImage imageWithData:                                                                                          [NSData dataWithContentsOfURL:location]];
                                                      _headSculptureImageView.image = downloadedImage;
//                                                      dispatch_async(dispatch_get_global_queue(0, 0), ^{
//                                                          // 处理耗时操作的代码块...
//                                                          
//                                                          //通知主线程刷新
//                                                          dispatch_async(dispatch_get_main_queue(), ^{
//                                                              //回调或者说是通知主线程刷新，
//                                                              
//                                                          });
//                                                      });
                                                  }];
    [downloadPhotoTask resume];
}



//网络连接返回数据
- (void)requestSuccessedWithResult:(id)result NSURLSessionTask:(NSURLSessionTask *)task sender:(id)sender{
    
    NSString * urlString = [NSString stringWithFormat:@"%@", task.currentRequest.URL];
    
    if ([result isKindOfClass:[NSDictionary class]]) {
        //        NSString * code = [NSString stringWithFormat:@"%@", [result objectForKey:@"retcode"]];
        if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"user/get_info"]]){
            _urlString = [NSString stringWithFormat:@"%@", [[result objectForKey:@"retmsg"] objectForKey:@"uhead"]];
            
            NSURL* imagePath = [NSURL URLWithString:_urlString];
            [_headSculptureImageView sd_setImageWithURL:imagePath];
                        
            _nameLabel.text = [NSString stringWithFormat:@"%@", [[result objectForKey:@"retmsg"] objectForKey:@"uname"]];
            _mobilePhoneLabel.text = [NSString stringWithFormat:@"%@", [[result objectForKey:@"retmsg"] objectForKey:@"uphone"]];
            NSString * sex = [NSString stringWithFormat:@"%@", [[result objectForKey:@"retmsg"] objectForKey:@"usex"]];
            if ([sex isEqualToString:@"0"]) {
                _sexLabel.text = @"男";
            }else if ([sex isEqualToString:@"1"]){
                _sexLabel.text = @"女";
            }
        }else if ([urlString isEqualToString:[NSString stringWithFormat:@"%@%@", URLDoman, @"user/modify"]]){
            [self alertViewShowWithAlertString:@"保存成功"];
        }
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark --toolBar懒加载
-(UIToolbar *)toolBar{
   if (_toolBar == nil) {
      _toolBar = [[UIToolbar alloc] init];
      _toolBar.frame = CGRectMake(0, 0, 0, 44);
      
      UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(leftItemCancel)];
      
      UIBarButtonItem *flexibleSpaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
      
      UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(rightItemCertain)];
      
      _toolBar.items = @[leftItem, flexibleSpaceItem, rightItem];
      
      _toolBar.backgroundColor = [UIColor whiteColor];
      _toolBar.tintColor = [UIColor colorWithRed:255/255.0 green:160/255.0 blue:4/255.0 alpha:1.0];
   }
   return _toolBar;
}

-(void)leftItemCancel{
   [self.view endEditing:YES];
}

-(void)rightItemCertain{
   _sexLabel.text = _tempSex;
   
   
   NSString * token = userObject.accessToken;
   NSString * uid = userObject.userID;
   
   NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
   [params setObject:token forKey:@"token"];
   [params setObject:uid forKey:@"uid"];
   [params setObject:@"0" forKey:@"udevice"];
   if ([_sexLabel.text isEqualToString:@"男"]) {
      [params setObject:@"0" forKey:@"usex"];
   }else if ([_sexLabel.text isEqualToString:@"女"]){
      [params setObject:@"1" forKey:@"usex"];
   }
   
   [self postRequestWithMethodName:@"user/modify" andParams:params andSender:nil];
   
   [self.view endEditing:YES];
}

#pragma mark --pickerView懒加载
-(UIPickerView *)pickerView{
   if (_pickerView == nil) {
      _pickerView = [[UIPickerView alloc] init];
      _pickerView.backgroundColor = [UIColor whiteColor];
      _pickerView.dataSource = self;
      _pickerView.delegate = self;
   }
   return _pickerView;
}

#pragma mark --pickerView数据源
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
   return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
   return 2;
}
#pragma mark --pickerView代理方法
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
   if (row == 0) {
      return @"男";
   } else {
      return @"女";
   }
}

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
   if (row == 0) {
      _tempSex = @"男";
   }else{
      _tempSex = @"女";
   }

}

@end
